package com.example.service;

import com.example.service.RbacService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

@Component("rbacService")
public class RbacServiceImpl implements RbacService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。
            String userName = ((UserDetails) principal).getUsername();
            //System.out.println("当前用户用户名是="+userName);

            Set<String> urls = new HashSet<>(); // 数据库读取 //读取用户所拥有权限的所有URL
            //接下来可以从数据库中读取该用户的资源列表，
            //然后add到 urls 上 例如：urls.add("/whoim");


            //管理员默认拥有所有权限
            if (userName.equals("admin")){
                urls.add("/**");
            }else{
                urls.add("/user/**");
            }

            //以下是默认开放的URL
            urls.add("/");
            urls.add("/home/**");
            urls.add("/about");

            // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}